// ConfigManager.cpp: implementation of the CConfigManager class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "GameStart.h"
#include "ConfigManager.h"
#include "CommFunc.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
 
CConfigManager* CConfigManager::m_pInstance = NULL; 
CConfigManager::CConfigManager()
{
	m_mapConfigItem.RemoveAll(); 
	ReadFromFile();
}

CConfigManager::~CConfigManager()
{ 
	m_mapConfigItem.RemoveAll();
	if(m_pInstance!=NULL)
	{
		delete m_pInstance;
		m_pInstance=NULL;
	}
}

CConfigManager* CConfigManager::CreateInstance()
{
	if(m_pInstance==NULL)
	{
		m_pInstance=new CConfigManager();
	}
	return m_pInstance;
}

BOOL CConfigManager::AddItem(CString strKey,CString strValue)
{
	if(FindKey(strKey).IsEmpty())
	{
		m_mapConfigItem.SetAt(strKey,strValue);
	}
	else
	{
		m_mapConfigItem.SetAt(strKey,strValue);
	}
	return TRUE;
}

BOOL CConfigManager::Clear()
{
	m_mapConfigItem.RemoveAll();
	return TRUE;
}

CString CConfigManager::FindKey(CString strKey)
{
	CString strValue=_T("");
	m_mapConfigItem.Lookup(strKey,strValue);
	return strValue;
}

BOOL CConfigManager::SaveToFile()
{
	try
	{
		CString strCFGFile = CCommFunc::CreateInstance()->GetBaseFilePath(_T("AppConfig.cfg"));
		CFile dataFile;
		if(!dataFile.Open(strCFGFile, CFile::modeCreate|CFile::modeWrite))
		{
			return FALSE;
		}
		CArchive ar(&dataFile,CArchive::store);
		m_mapConfigItem.Serialize(ar);  
		ar.Flush();
		ar.GetFile()->Close();
		ar.Close();
		return TRUE;
	}
	catch (CException* e) 
	{
		if(e!=NULL)
		{
			TCHAR tcMSG[MAX_PATH]={0};
			e->GetErrorMessage(tcMSG,MAX_PATH-1);
			CString strMessage=_T("");
			strMessage.Format(_T("%s"),tcMSG);
			AfxMessageBox(strMessage);
		}
		return FALSE;
	}
}


BOOL CConfigManager::ReadFromFile()
{
	try
	{
		CString strCFGFile = CCommFunc::CreateInstance()->GetBaseFilePath(_T("AppConfig.cfg"));
		CFile dataFile;
		if(!dataFile.Open(strCFGFile, CFile::modeRead))
		{
			return FALSE;
		}
		CArchive ar(&dataFile,CArchive::load);
		m_mapConfigItem.Serialize(ar); 
		ar.Flush();
		ar.GetFile()->Close();
		ar.Close();
		return TRUE;
	}
	catch (CException* e) 
	{
		if(e!=NULL)
		{
			TCHAR tcMSG[MAX_PATH]={0};
			e->GetErrorMessage(tcMSG,MAX_PATH-1);
			CString strMessage=_T("");
			strMessage.Format(_T("%s"),tcMSG);
			AfxMessageBox(strMessage);
		}
		return FALSE;
	}
}